package com.qingxin.sys.filter;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.util.AntPathMatcher;

/**
 * 设置通用过滤规则，拦截规则：同时符合拦截
 * @author Administrator
 *
 */
public class BaseInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 拦截的请求，默认拦截所有请求
	 */
	private String[] includePath = new String[] { "/**" };

	/**
	 * 放行的请求，为拦截请求includePath的一部分
	 */
	private String[] excludePath;

	
	/**
	 * 判断指定请求是否匹配指定规则
	 * @param mapping
	 * @param request
	 * @return
	 */
	private boolean match(String[] mapping, HttpServletRequest request) {
		if (mapping != null) {
			String path = request.getContextPath();
			if(path.endsWith("/")){
				path = path.substring(0, path.length() - 1);
			}
			String requestURI = request.getRequestURI();
			requestURI = requestURI.substring(path.length());
			AntPathMatcher matcher = new AntPathMatcher();
			for(String pattern : mapping) {
				if(matcher.match(pattern, requestURI)) {
					return true;
				}
			}
		}
		return false;
	}

	
	/**
	 * 判断是否需要拦截
	 * @param request
	 * @return
	 */
	protected boolean shouldIntercept(HttpServletRequest request) {
		if (match(includePath, request)) {//符合拦截规则
			if (match(excludePath, request)) {//符合放行规则
				return false;
			}
			return true;
		}
		return false;
	}

	
	public String[] getIncludePath() {
		return includePath;
	}
	
	public void setIncludePath(String[] includePath) {
		this.includePath = includePath;
	}
	
	public String[] getExcludePath() {
		return excludePath;
	}

	public void setExcludePath(String[] excludePath) {
		this.excludePath = excludePath;
	}
	
}